package client;

import static debug.Debug.DBUG;
import java.io.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.swing.ImageIcon;

public class MapReader {

	private HashMap<Character,ImageIcon> files = new HashMap<Character, ImageIcon>();
	private ImageIcon[][] images;
	
	private void initFiles(){
		char[] signs = {'a', 'b'};
		File[] file = {new File("F:/programmering/Java/workspace/priv/Alfa Client/img/lava.png"),
				new File("F:/programmering/Java/workspace/priv/Alfa Client/img/grass.png")
					};
						
		
		for (File fil: file) {
			if (!fil.exists()) {
				DBUG("tilefile not found");
			}
		}
		for (int i=0; i<signs.length; i++) {
			try {
				files.put(signs[i],new ImageIcon(file[i].toURI().toURL()));
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}
		DBUG("mapReader, should be 2+: "+ files.size());
	}
	
	public MapReader(String map){
		List<List<ImageIcon>> imageArray = new ArrayList<List<ImageIcon>>();
		initFiles();
		File file = new File("F:/programmering/Java/workspace/priv/Alfa Client/map/"+ map +".txt");
		if (!file.exists()) {
			DBUG("mapfile not found");
		}
		try {
		    BufferedReader br = new BufferedReader(
		                        new InputStreamReader(
		                        new FileInputStream(file)));
		    String line;
		    int j=0;
		    while((line = br.readLine()) != null){
		    	imageArray.add(new ArrayList<ImageIcon>());
		        for(int i=0;i<line.length();i++){
		        	imageArray.get(j).add(files.get(line.charAt(i)));
		        }
		        j++;
		    }
		    br.close();
		} catch(IOException e) {
		    
		}
		listToArray(imageArray);
	}

	private void listToArray(List<List<ImageIcon>> imageArray ){
		images = new ImageIcon[imageArray.size()][imageArray.get(0).size()];
		for(int y=0;y<imageArray.size();y++){
			for(int x=0;x<imageArray.get(y).size();x++){
				images[x][y]=imageArray.get(y).get(x);
			}
		}
	}
	
	public ImageIcon[][] getImages(){
		return images;
	}
	
}
